<template>
  <div class="messages-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">private message</h1>
        <div class="header-actions">
          <el-badge :value="unreadCount" :hidden="unreadCount === 0" class="unread-badge">
            <el-icon size="20"><ChatDotRound /></el-icon>
          </el-badge>
        </div>
      </div>
    </div>

    <div class="messages-container">
      <!-- 会话列表 -->
      <div class="conversation-list">
        <div class="list-header">
          <h3>Conversation List</h3>
          <el-button
            type="text"
            size="small"
            @click="refreshConversations"
            :loading="conversationsLoading"
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
        </div>

        <!-- 加载状态 -->
        <div v-if="conversationsLoading && conversations.length === 0" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>

        <!-- 会话列表 -->
        <div v-else-if="conversations.length > 0" class="conversations">
          <div
            v-for="conversation in conversations"
            :key="conversation.id"
            class="conversation-item"
            :class="{ active: selectedConversationId === conversation.id }"
            @click="selectConversation(conversation.id)"
          >
            <el-avatar
              :size="48"
              :src="getUserAvatar(conversation.otherUser?.avatar)"
              class="user-avatar"
            >
              {{ conversation.otherUser?.nickname?.charAt(0) }}
            </el-avatar>

            <div class="conversation-info">
              <div class="user-info">
                <span class="username">{{ conversation.otherUser?.nickname }}</span>
                <span v-if="conversation.otherUser?.isOnline" class="online-status">在线</span>
              </div>

              <div class="last-message">
                <span class="message-content">
                  {{ getLastMessageDisplay(conversation.lastMessage) }}
                </span>
                <span class="message-time">
                  {{ formatTime(conversation.lastMessageTime) }}
                </span>
              </div>
            </div>

            <div class="conversation-meta">
              <el-badge
                :value="conversation.unreadCount"
                :hidden="conversation.unreadCount === 0"
                class="unread-count"
              />
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-conversations">
          <el-empty
            :image-size="120"
            description="暂无私信会话"
          >
            <template #image>
              <el-icon size="120" color="#d3d3d3"><ChatDotRound /></el-icon>
            </template>
          </el-empty>
        </div>
      </div>

      <!-- 聊天区域 -->
      <div class="chat-area">
        <!-- 未选择会话 -->
        <div v-if="!selectedConversationId" class="no-conversation">
          <el-icon size="80" color="#d3d3d3"><ChatDotRound /></el-icon>
          <h3>Choose a conversation to start chatting</h3>
          <p>Select a conversation from the left, or click the "Send Private Message" button on the user's homepage to start a new conversation</p>
        </div>

        <!-- 聊天界面 -->
        <div v-else class="chat-container">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="chat-user-info">
              <el-avatar
                :size="40"
                :src="getUserAvatar(selectedConversation.otherUser?.avatar)"
                class="user-avatar"
              >
                {{ selectedConversation.otherUser?.nickname?.charAt(0) }}
              </el-avatar>
              <div class="user-details">
                <span class="username">{{ selectedConversation.otherUser?.nickname }}</span>
                <span class="online-status" :class="{ online: selectedConversation.otherUser?.isOnline }">
                  {{ selectedConversation.otherUser?.isOnline ? 'Online' : 'Offline' }}
                </span>
              </div>
            </div>

            <div class="chat-actions">
              <el-button type="text" @click="viewUserProfile">
                <el-icon><User /></el-icon>
                View profile
              </el-button>
            </div>
          </div>

          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <!-- 加载更多 -->
            <div v-if="hasMoreMessages" class="load-more">
              <el-button
                type="text"
                size="small"
                @click="loadMoreMessages"
                :loading="messagesLoading"
              >
                Load more messages
              </el-button>
            </div>

            <!-- 消息列表 -->
            <div class="messages-list">
              <div
                v-for="(message, index) in messages"
                :key="message.id"
                class="message-item"
                :class="{ 
                  'is-self': message.isSelf,
                  'is-continuous': isContinuousMessage(message, index)
                }"
              >
                <div class="message-wrapper">
                  <div class="message-avatar" v-if="!isContinuousMessage(message, index)">
                    <el-avatar
                      :size="32"
                      :src="getUserAvatar(message.sender?.avatar)"
                    >
                      {{ message.sender?.nickname?.charAt(0) }}
                    </el-avatar>
                  </div>
                  <div class="message-avatar-placeholder" v-else></div>

                  <div class="message-content">
                    <div class="message-bubble">
                      <!-- 文本消息 -->
                      <div v-if="message.messageType === 1" class="text-message">
                        {{ message.content }}
                      </div>

                      <!-- 图片消息 -->
                      <div v-else-if="message.messageType === 2" class="image-message">
                        <el-image
                          :src="getMediaUrl(message.mediaUrl)"
                          fit="cover"
                          class="message-image"
                          :preview-src-list="[getMediaUrl(message.mediaUrl)]"
                        />
                      </div>

                      <!-- 其他类型消息 -->
                      <div v-else class="other-message">
                        {{ getMessageTypeDisplay(message.messageType) }}
                      </div>

                      <!-- 消息状态 -->
                      <div v-if="message.status === 3" class="recalled-message">
                        Message has been recalled
                      </div>
                    </div>

                    <div class="message-meta">
                      <span class="message-time">{{ formatTime(message.createdTime) }}</span>
                      <span v-if="message.isSelf && message.isRead" class="read-status">Read</span>

                      <!-- 撤回按钮 -->
                      <el-button
                        v-if="message.isSelf && message.status === 1 && canRecallMessage(message)"
                        type="text"
                        size="small"
                        @click="recallMessage(message.id)"
                      >
                        Recall
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="input-area">
            <div class="input-toolbar">
              <el-button type="text" @click="selectImage">
                <el-icon><Picture /></el-icon>
              </el-button>
              <el-button type="text" @click="selectFile">
                <el-icon><Paperclip /></el-icon>
              </el-button>
            </div>

            <div class="input-container">
              <el-input
                v-model="messageInput"
                type="textarea"
                :rows="3"
                placeholder="Enter message..."
                @keydown.enter.exact="sendMessage"
                @keydown.enter.ctrl="addNewLine"
                class="message-input"
              />

              <div class="input-actions">
                <span class="input-tip">Enter to send, Ctrl+Enter to add a new line</span>
                <el-button
                  type="primary"
                  @click="sendMessage"
                  :disabled="!messageInput.trim()"
                  :loading="sendingMessage"
                >
                  Send
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件上传 -->
    <input
      ref="imageInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="handleImageSelect"
    />

    <input
      ref="fileInput"
      type="file"
      style="display: none"
      @change="handleFileSelect"
    />
  </div>
</template>

<script setup>
import {nextTick, onMounted, reactive, ref, watch, computed} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useUserStore} from '@/stores/user'
import {getMediaUrl, getUserAvatar} from '@/utils/media'
import {formatTime} from '@/utils/format'
import {
  getConversationList,
  getConversationMessages,
  getOrCreateConversation,
  getUnreadMessageCount,
  markConversationAsRead,
  recallMessage as recallMessageApi,
  sendMessage as sendMessageApi
} from '@/api/message'
import {useChat} from '@/composables/useChat';
import {uploadFile} from '@/api/attach'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// WebSocket连接
const { isConnected, sendMessage: sendWsMessage, onMessage } = useChat()

// 响应式数据
const conversations = ref([])
const messages = ref([])
const selectedConversationId = ref(null) // 只存储会话ID
const messageInput = ref('')
const unreadCount = ref(0)
const currentUserId = ref('')

// 计算属性：获取当前选中的会话对象
const selectedConversation = computed(() => {
  if (!selectedConversationId.value) return null
  return conversations.value.find(c => c.id === selectedConversationId.value) || null
})

// 加载状态
const conversationsLoading = ref(false)
const messagesLoading = ref(false)
const sendingMessage = ref(false)
const hasMoreMessages = ref(false)

// 分页参数
const conversationPagination = reactive({
  pageNum: 1,
  pageSize: 20
})

const messagePagination = reactive({
  pageNum: 1,
  pageSize: 50
})

// DOM引用
const messagesContainer = ref(null)
const imageInput = ref(null)
const fileInput = ref(null)

// 监听路由参数变化
watch(() => route.query.userId, (newUserId) => {
  if (newUserId && userStore.isLoggedIn) {
    createConversationWithUser(newUserId)
  }
}, { immediate: false })

// 初始化
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  await getCurrentUserId()
  await loadConversations()
  await loadUnreadCount()

  // 如果URL中有userId参数，创建或打开与该用户的会话
  if (route.query.userId) {
    await createConversationWithUser(route.query.userId)
  }

  // 注册WebSocket消息处理
  onMessage('private_message', handleWebSocketMessage)

  // 检查WebSocket连接状态
  setTimeout(() => {
    console.log('WebSocket连接状态:', isConnected.value)
    if (!isConnected.value) {
      console.warn('WebSocket未连接，可能无法接收实时消息')
    }
  }, 2000)
})



// 加载会话列表
const loadConversations = async () => {
  try {
    conversationsLoading.value = true
    const response = await getConversationList({
      pageNum: conversationPagination.pageNum,
      pageSize: conversationPagination.pageSize
    })

    if (response.code === 200) {
      conversations.value = response.data.data || []
    } else {
      ElMessage.error(response.message || '加载会话列表失败')
    }
  } catch (error) {
    console.error('加载会话列表失败:', error)
    ElMessage.error('加载会话列表失败')
  } finally {
    conversationsLoading.value = false
  }
}

// 刷新会话列表
const refreshConversations = () => {
  conversationPagination.pageNum = 1
  loadConversations()
}

// 选择会话
const selectConversation = async (conversationId) => {
  selectedConversationId.value = conversationId

  // 清空消息列表
  messages.value = []

  // 加载消息
  await loadMessages(conversationId)

  // 标记为已读
  const conversation = conversations.value.find(c => c.id === conversationId)
  if (conversation && conversation.unreadCount > 0) {
    try {
      await markConversationAsRead(conversationId)
      // 更新本地未读数
      unreadCount.value -= conversation.unreadCount
      conversation.unreadCount = 0
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }

  // 滚动到底部
  await nextTick(() => {
    scrollToBottom()
  })
}

// 加载消息列表
const loadMessages = async (conversationId) => {
  try {
    messagesLoading.value = true
    const response = await getConversationMessages(conversationId, {
      pageNum: messagePagination.pageNum,
      pageSize: messagePagination.pageSize
    })

    if (response.code === 200) {
      const newMessages = response.data.data || []

      if (messagePagination.pageNum === 1) {
        // 首次加载：将消息反转，让最早的消息在上面，最新的在下面
        messages.value = newMessages.reverse()
        // 初次加载消息后滚动到底部
        await nextTick(() => {
          scrollToBottom()
        })
      } else {
        // 加载更多历史消息：新消息（更早的）添加到前面，但要保持正确的时间顺序
        messages.value = [...newMessages.reverse(), ...messages.value]
      }

      hasMoreMessages.value = newMessages.length === messagePagination.pageSize
    } else {
      ElMessage.error(response.message || '加载消息失败')
    }
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  } finally {
    messagesLoading.value = false
  }
}

// 加载更多消息
const loadMoreMessages = () => {
  if (hasMoreMessages.value && !messagesLoading.value) {
    messagePagination.pageNum++
    loadMessages(selectedConversationId.value)
  }
}

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim() || !selectedConversationId.value) return

  const currentChat = conversations.value.find(c => c.id === selectedConversationId.value)
  if (!currentChat) return

  try {
    sendingMessage.value = true
    const messageData = {
      receiverId: currentChat.otherUser.userId,
      messageType: 1, // 文本消息
      content: messageInput.value.trim()
    }

    const response = await sendMessageApi(messageData)

    if (response.code === 200) {
      // 添加到本地消息列表
      const newMsg = {
        id: response.data.id,
        content: messageInput.value.trim(),
        messageType: 1,
        isSelf: true,
        sendTime: response.data.sendTime || new Date().toISOString(),
        createdTime: response.data.createdTime || new Date().toISOString(),
        sender: {
          userId: currentUserId.value,
          nickname: userStore.userInfo?.nickname,
          avatar: userStore.userInfo?.avatar
        },
        isRead: false
      }

      messages.value.push(newMsg)

      // 更新会话的最后消息
      currentChat.lastMessage = messageInput.value.trim()
      currentChat.lastMessageTime = newMsg.sendTime

      console.log('消息发送成功，WebSocket连接状态:', isConnected.value)

      messageInput.value = ''

      // 滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    } else {
      throw new Error(response.message || '发送失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error(error.message || '发送消息失败')
  } finally {
    sendingMessage.value = false
  }
}

// 添加换行
const addNewLine = () => {
  messageInput.value += '\n'
}

// 标记为已读
const markAsRead = async (conversationId) => {
  try {
    await markConversationAsRead(conversationId)

    // 更新本地会话的未读数
    const conversation = conversations.value.find(c => c.id === conversationId)
    if (conversation) {
      conversation.unreadCount = 0
    }

    // 更新总未读数
    await loadUnreadCount()
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

// 撤回消息
const recallMessage = async (messageId) => {
  try {
    await ElMessageBox.confirm('确定要撤回这条消息吗？', '撤回消息', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await recallMessageApi(messageId)

    // 更新本地消息状态
    const message = messages.value.find(m => m.id === messageId)
    if (message) {
      message.status = 3 // 已撤回
    }

    ElMessage.success('消息已撤回')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回消息失败:', error)
      ElMessage.error('撤回消息失败')
    }
  }
}

// 加载未读消息数
const loadUnreadCount = async () => {
  try {
    const response = await getUnreadMessageCount()
    if (response.code === 200) {
      unreadCount.value = response.data || 0
    }
  } catch (error) {
    console.error('加载未读消息数失败:', error)
  }
}

// 创建与指定用户的会话
const createConversationWithUser = async (userId) => {
  try {
    const response = await getOrCreateConversation(userId)
    if (response.code === 200) {
      const conversation = response.data

      // 检查会话是否已存在于列表中
      const existingIndex = conversations.value.findIndex(c => c.id === conversation.id)
      if (existingIndex >= 0) {
        // 更新现有会话
        conversations.value[existingIndex] = conversation
      } else {
        // 添加新会话到列表顶部
        conversations.value.unshift(conversation)
      }

      // 选择这个会话
      await selectConversation(conversation.id)

      // 清除URL参数
      router.replace({ path: '/messages' })
    } else {
      ElMessage.error(response.message || '创建会话失败')
    }
  } catch (error) {
    console.error('创建会话失败:', error)
    ElMessage.error('创建会话失败')
  }
}

// 查看用户资料
const viewUserProfile = () => {
  if (selectedConversation.value?.otherUser?.userId) {
    router.push(`/people/${selectedConversation.value.otherUser.userId}`)
  }
}

// 判断是否为连续消息（同一人发送的相邻消息）
const isContinuousMessage = (message, index) => {
  if (index === 0) return false

  const prevMessage = messages.value[index - 1]
  if (!prevMessage) return false

  // 检查是否为同一发送者
  const isSameSender = message.sender?.userId === prevMessage.sender?.userId

  // 检查时间间隔是否小于5分钟
  // 使用sendTime或createdTime，优先使用sendTime
  const currentTime = new Date(message.sendTime || message.createdTime).getTime()
  const prevTime = new Date(prevMessage.sendTime || prevMessage.createdTime).getTime()
  const timeDiff = currentTime - prevTime
  const isWithinTimeLimit = timeDiff < 5 * 60 * 1000 // 5分钟

  return isSameSender && isWithinTimeLimit
}

// 选择图片
const selectImage = () => {
  imageInput.value?.click()
}

// 选择文件
const selectFile = () => {
  fileInput.value?.click()
}

// 处理图片选择
const handleImageSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  try {
    sendingMessage.value = true

    // 上传图片
    const uploadResponse = await uploadFile(file)
    if (uploadResponse.code !== 200) {
      ElMessage.error('图片上传失败')
      return
    }

    // 发送图片消息
    const response = await sendMessageApi({
      receiverId: selectedConversation.value.otherUser.userId,
      messageType: 2, // 图片消息
      mediaUrl: uploadResponse.data.filePath
    })

    if (response.code === 200) {
      messages.value.push(response.data)
      updateConversationLastMessage(response.data)

      nextTick(() => {
        scrollToBottom()
      })
    } else {
      ElMessage.error(response.message || '发送图片失败')
    }
  } catch (error) {
    console.error('发送图片失败:', error)
    ElMessage.error('发送图片失败')
  } finally {
    sendingMessage.value = false
    // 清空文件选择
    event.target.value = ''
  }
}

// 处理文件选择
const handleFileSelect = async (event) => {
  const file = event.target.files[0]
  if (!file) return

  try {
    sendingMessage.value = true

    // 上传文件
    const uploadResponse = await uploadFile(file)
    if (uploadResponse.code !== 200) {
      ElMessage.error('文件上传失败')
      return
    }

    // 发送文件消息
    const response = await sendMessageApi({
      receiverId: selectedConversation.value.otherUser.userId,
      messageType: 4, // 文件消息
      content: file.name,
      mediaUrl: uploadResponse.data.filePath
    })

    if (response.code === 200) {
      messages.value.push(response.data)
      updateConversationLastMessage(response.data)

      nextTick(() => {
        scrollToBottom()
      })
    } else {
      ElMessage.error(response.message || '发送文件失败')
    }
  } catch (error) {
    console.error('发送文件失败:', error)
    ElMessage.error('发送文件失败')
  } finally {
    sendingMessage.value = false
    // 清空文件选择
    event.target.value = ''
  }
}



// WebSocket消息处理
const handleWebSocketMessage = (wsData) => {
  console.log('收到WebSocket消息:', wsData)

  if (wsData.type === 'private_message') {
    const messageData = wsData.data
    console.log('处理私信消息:', messageData)

    // 如果是当前会话的消息，添加到消息列表
    if (messageData.conversationId === selectedConversationId.value) {
      const newMsg = {
        id: messageData.messageId,
        content: messageData.content,
        messageType: messageData.messageType || 1,
        isSelf: messageData.sender?.userId === currentUserId.value,
        sendTime: messageData.sendTime,
        createdTime: messageData.sendTime,
        sender: messageData.sender,
        mediaUrl: messageData.mediaUrl,
        isRead: false
      }

      messages.value.push(newMsg)
      console.log('消息已添加到当前会话')

      // 滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
    }

    // 更新会话列表中的最后消息
    const conversation = conversations.value.find(c => c.id === messageData.conversationId)
    if (conversation) {
      conversation.lastMessage = messageData.content
      conversation.lastMessageTime = messageData.sendTime

      // 如果不是当前会话，增加未读数
      if (messageData.conversationId !== selectedConversationId.value) {
        conversation.unreadCount = (conversation.unreadCount || 0) + 1
        unreadCount.value += 1
      }
      console.log('会话列表已更新')
    } else {
      console.log('未找到对应的会话，重新加载会话列表')
      // 如果找不到会话，重新加载会话列表
      loadConversations()
    }
  }
}

// 处理消息撤回
const handleMessageRecall = (recallData) => {
  const message = messages.value.find(m => m.id === recallData.messageId)
  if (message) {
    message.status = 3 // 已撤回
  }
}

// 处理在线状态变化
const handleOnlineStatusChange = (data) => {
  // 更新会话列表中用户的在线状态
  conversations.value.forEach(conversation => {
    if (conversation.otherUser?.userId === data.userId) {
      conversation.otherUser.isOnline = data.isOnline
    }
  })

  // 更新当前选中会话的在线状态
  if (selectedConversation.value?.otherUser?.userId === data.userId) {
    selectedConversation.value.otherUser.isOnline = data.isOnline
  }
}

// 更新会话最后消息
const updateConversationLastMessage = (message) => {
  const conversation = conversations.value.find(c => c.id === message.conversationId)
  if (conversation) {
    conversation.lastMessage = {
      messageId: message.id,
      messageType: message.messageType,
      content: message.content,
      senderId: message.sender.userId,
      isSelf: message.isSelf,
      sendTime: message.sendTime
    }
    conversation.lastMessageTime = message.sendTime

    // 将会话移到列表顶部
    const index = conversations.value.indexOf(conversation)
    if (index > 0) {
      conversations.value.splice(index, 1)
      conversations.value.unshift(conversation)
    }
  }
}

// 更新会话（收到新消息时）
const updateConversationWithNewMessage = (messageData) => {
  let conversation = conversations.value.find(c => c.id === messageData.conversationId)

  if (conversation) {
    // 更新现有会话
    conversation.lastMessage = {
      messageId: messageData.id,
      messageType: messageData.messageType,
      content: messageData.content,
      senderId: messageData.sender.userId,
      isSelf: false,
      sendTime: messageData.sendTime
    }
    conversation.lastMessageTime = messageData.sendTime

    // 如果不是当前选中的会话，增加未读数
    if (selectedConversationId.value !== messageData.conversationId) {
      conversation.unreadCount = (conversation.unreadCount || 0) + 1
    }

    // 将会话移到列表顶部
    const index = conversations.value.indexOf(conversation)
    if (index > 0) {
      conversations.value.splice(index, 1)
      conversations.value.unshift(conversation)
    }
  } else {
    // 如果会话不存在，重新加载会话列表
    loadConversations()
  }
}

// 获取当前用户ID
const getCurrentUserId = async () => {
  try {
    if (userStore.userInfo?.userId) {
      currentUserId.value = userStore.userInfo.userId
      return
    }
    console.warn('未找到用户信息，请确保已登录')
  } catch (error) {
    console.error('获取用户ID失败:', error)
  }
}

// 工具方法
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

const getLastMessageDisplay = (lastMessage) => {
  if (!lastMessage) return 'No message'

  if (lastMessage.messageType === 1) {
    return lastMessage.content
  } else if (lastMessage.messageType === 2) {
    return '[Image]'
  } else if (lastMessage.messageType === 3) {
    return '[Video]'
  } else if (lastMessage.messageType === 4) {
    return '[File]'
  }

  return '[Unknown message]'
}

const getMessageTypeDisplay = (messageType) => {
  switch (messageType) {
    case 2: return '[Image]'
    case 3: return '[Video]'
    case 4: return '[File]'
    default: return '[Unknown message type]'
  }
}

const canRecallMessage = (message) => {
  // 只能撤回2分钟内的消息
  const now = new Date()
  const sendTime = new Date(message.sendTime)
  const diffMinutes = (now - sendTime) / (1000 * 60)
  return diffMinutes <= 2
}
</script>

<style lang="scss" scoped>
.messages-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: $background-light;
}

.page-header {
  background: $background-color;
  border-bottom: 1px solid $border-light;
  padding: 16px 24px;

  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    max-width: 1200px;
    margin: 0 auto;
  }

  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: $text-color;
    margin: 0;
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .unread-badge {
    :deep(.el-badge__content) {
      background-color: $primary-color;
    }
  }
}

.messages-container {
  flex: 1;
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  height: calc(100vh - 80px);
}

.conversation-list {
  width: 320px;
  background: $background-color;
  border-right: 1px solid $border-light;
  display: flex;
  flex-direction: column;

  .list-header {
    padding: 16px 20px;
    border-bottom: 1px solid $border-light;
    display: flex;
    align-items: center;
    justify-content: space-between;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: $text-color;
    }
  }

  .loading-container {
    padding: 20px;
  }

  .conversations {
    flex: 1;
    overflow-y: auto;
  }

  .conversation-item {
    display: flex;
    align-items: center;
    padding: 16px 20px;
    cursor: pointer;
    border-bottom: 1px solid $border-light;
    transition: background-color 0.2s ease;

    &:hover {
      background-color: $background-light;
    }

    &.active {
      background-color: rgba($primary-color, 0.1);
      border-right: 3px solid $primary-color;
    }

    .user-avatar {
      flex-shrink: 0;
      margin-right: 12px;
    }

    .conversation-info {
      flex: 1;
      min-width: 0;

      .user-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;

        .username {
          font-weight: 500;
          color: $text-color;
          font-size: 14px;
        }

        .online-status {
          font-size: 12px;
          color: $success-color;
          background: rgba($success-color, 0.1);
          padding: 2px 6px;
          border-radius: 10px;
        }
      }

      .last-message {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .message-content {
          color: $text-secondary;
          font-size: 13px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          flex: 1;
          margin-right: 8px;
        }

        .message-time {
          color: $text-light;
          font-size: 12px;
          flex-shrink: 0;
        }
      }
    }

    .conversation-meta {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 4px;

      .unread-count {
        :deep(.el-badge__content) {
          background-color: $primary-color;
        }
      }
    }
  }

  .empty-conversations {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
  }
}

.chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: $background-color;

  .no-conversation {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    padding: 40px;

    h3 {
      margin: 16px 0 8px;
      color: $text-color;
      font-size: 18px;
    }

    p {
      color: $text-secondary;
      line-height: 1.6;
      max-width: 400px;
    }
  }

  .chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .chat-header {
    padding: 16px 24px;
    border-bottom: 1px solid $border-light;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: $background-color;

    .chat-user-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .user-details {
        .username {
          display: block;
          font-weight: 500;
          color: $text-color;
          font-size: 16px;
          margin-bottom: 2px;
        }

        .online-status {
          font-size: 12px;
          color: $text-light;

          &.online {
            color: $success-color;
          }
        }
      }
    }

    .chat-actions {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }

  .messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px 24px;
    background: $background-light;
    min-height: 0; // 重要：允许flex子项收缩

    .load-more {
      text-align: center;
      padding: 16px 0;
    }

    .messages-list {
      display: flex;
      flex-direction: column;
      min-height: 100%;
      padding-bottom: 20px;
      width: 100%;
    }

    .message-item {
      width: 100%;
      margin-bottom: 12px;

      &.is-continuous {
        margin-bottom: 4px;
        
        .message-meta {
          display: none;
        }
      }

      // 对方的消息 - 左对齐
      &:not(.is-self) {
        .message-wrapper {
          display: flex;
          align-items: flex-start;
          justify-content: flex-start;
          max-width: 70%;

          .message-avatar {
            flex-shrink: 0;
            margin-right: 8px;
          }

          .message-content {
            .message-bubble {
              background: #f0f0f0;
              color: #333;
              border-radius: 18px 18px 18px 4px;
              border: none;
              box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
              font-size: 14px;
              line-height: 1.5;
            }

            .message-meta {
              text-align: left;
            }
          }
        }
      }

      // 自己的消息 - 右对齐
      &.is-self {
        display: flex;
        justify-content: flex-end;

        .message-wrapper {
          display: flex;
          align-items: flex-start;
          flex-direction: row-reverse;
          max-width: 70%;

          .message-avatar {
            flex-shrink: 0;
            margin-left: 8px;
          }

          .message-avatar-placeholder {
            width: 32px;
            margin-left: 8px;
            margin-right: 0;
          }

          .message-content {
            .message-bubble {
              background: #b92b27;
              color: white;
              border-radius: 18px 18px 4px 18px;
              border: none;
              box-shadow: 0 1px 3px rgba(22, 119, 255, 0.2);
              font-size: 14px;
              line-height: 1.5;
            }

            .message-meta {
              text-align: right;
              flex-direction: row-reverse;
            }
          }
        }
      }

      .message-wrapper {
        .message-avatar {
          width: 32px;
          height: 32px;
        }

        .message-avatar-placeholder {
          width: 32px;
          height: 32px;
          margin-right: 8px;
          flex-shrink: 0;
        }

        .message-content {
          display: flex;
          flex-direction: column;

          .message-bubble {
            padding: 12px 16px;
            box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
            word-wrap: break-word;

            .text-message {
              line-height: 1.5;
              white-space: pre-wrap;
            }

            .image-message {
              .message-image {
                max-width: 200px;
                max-height: 200px;
                border-radius: 8px;
                cursor: pointer;
              }
            }

            .other-message {
              color: $text-secondary;
              font-style: italic;
            }

            .recalled-message {
              color: $text-light;
              font-style: italic;
              font-size: 13px;
              opacity: 0.7;
            }
          }

          .message-meta {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-top: 6px;
            opacity: 0.8;

            .message-time {
              font-size: 11px;
              color: $text-light;
            }

            .read-status {
              font-size: 11px;
              color: $success-color;
              font-weight: 500;
            }
          }
        }
      }
    }
  }

  .input-area {
    border-top: 1px solid $border-light;
    background: $background-color;

    .input-toolbar {
      padding: 12px 24px 0;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .input-container {
      padding: 12px 24px 16px;

      .message-input {
        margin-bottom: 8px;

        :deep(.el-textarea__inner) {
          border-radius: 8px;
          resize: none;
        }
      }

      .input-actions {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .input-tip {
          font-size: 12px;
          color: $text-light;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .messages-container {
    flex-direction: column;
    height: auto;
  }

  .conversation-list {
    width: 100%;
    height: 300px;
  }

  .chat-area {
    height: calc(100vh - 380px);
  }
}
</style>
